import React from 'react';
import {Button, Icon, Tree, Spin, message} from 'antd';
import {WeaTools, WeaDialog, WeaInputNumber,WeaMoreButton, WeaFormItem, WeaInput, WeaSelect, WeaHelpfulTip,WeaLocaleProvider, WeaCheckbox, WeaBrowser} from 'ecCom';
const getLabel = WeaLocaleProvider.getLabel;
import * as lodash from 'lodash';
import { toJS } from 'mobx';
import EOrderCol from './base/EOderCol';
import EField_New from './base/EField_New';
const TreeNode = Tree.TreeNode;
import { InputNumber } from 'antd';
// 流程中心，数据来源
class Main extends React.Component {
    constructor(props) {
        super(props);
        this.getButtons = this.getButtons.bind(this);
        this.onOk = this.onOk.bind(this);
        this.onCancel = this.onCancel.bind(this);

        const {settingData = {}} = props;
        this.state = {
            visible: true,
            id: settingData.id,
            orderColVisible: false,
            eFieldNewVisible: false,
            ...this.getStateVaule(settingData)
        };
    }
  
    getStateVaule = (data) => {
      return {
        wfsourceOption: this.getOptionSelected(data).options || [], //流程来源选项
        wfsourceSelectkey: this.getOptionSelected(data).selectedKey || '',
        workflowids: '', //工作流浏览选中值
        workflowtypes: '', //流程类型浏览选中值
        orderColDataSource: data.condition && data.condition.orderColDatas || [], //排序字段
        orderColUsedKeys: data.condition && data.condition.orderColSelects && data.condition.orderColSelects.split(',') || [],
        eFieldNewDataSource: data.condition && data.condition.showColDatas || [], //显示字段
        eFieldNewUsedKeys:  data.condition && data.condition.showColSelects && data.condition.showColSelects.split(',') || [],
        dimensionalityDataSouce: data.condition && data.condition.showtypeidDatas || [], //显示维度
        dimensionalityUsedKeys : data.condition &&  data.condition.showtypeidSelects && data.condition.showtypeidSelects.split(',') || [],
        wfCount: data.wfCount || 10,
      }
    }
    componentWillReceiveProps(nextPorps) {
      const {settingData = {}} = nextPorps;
      this.setState(this.getStateVaule(settingData));
    }
    //获取下拉选择默认选中项
    getOptionSelected = (data) => {
      let str = ''; 
      let items = [];
      items = toJS(data).condition && toJS(data).condition.items.filter(v => {
        return v.domkey[0] == 'fromType'
      })
      if(items) {
        items.length > 0 && items[0].options.map(i => {
          if(i.selected) str += i.key; 
        })
        return {options: items.options, selectedKey: str};
      } else {
        return {options: [], selectedKey: ''}
      }
    }

    //获取显示字段默认选中项
    geteFieldNewUsedKeys = (data) => {
      let eFieldNewUsedKeys = []
      data.condition.showColDatas && data.condition.showColDatas.map( v => {
        if(v.scope == '1') {
          eFieldNewUsedKeys.push(v.id);
        }
      })  
      return eFieldNewUsedKeys;
    }
    
    //显示条数设置
    setCountChange = value => {
      this.setState({
        wfCount: value
      })
    }
    getButtons() {
        let buttons = [];
        buttons.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@h1eyg1@save`} type="primary" onClick={this.onOk}>{getLabel(86,"保存")}</Button> );
        buttons.push(<WeaMoreButton ecId={`${this && this.props && this.props.ecId || ''}_WeaMoreButton@bmpndu@more`}
          datas={[
            {
              key: "save",
              icon: <i className='icon-coms-Preservation'/>,
              content:getLabel(86,"保存"),
              onClick: () => {}
            }
          ]}
          collectParams={status.collectParams}>更多</WeaMoreButton> );
        return buttons;
    }

    onOk() {
      let passParams = {
        workflowids: this.state.workflowids,
        workflowtypes: this.state.workflowtypes,
        showcol: this.state.eFieldNewUsedKeys.join(','),
        fromType:  this.state.wfsourceSelectkey,
        ordercol: '',
        showtypeids: this.state.dimensionalityUsedKeys.join(','),
        perpagewfcenter: this.state.wfCount
      }
      let arr = [];
      this.state.orderColDataSource.map ( i => {
        this.state.orderColUsedKeys.map( (j,index) => {
          if(i.id == j) {
            arr.push( i.id + '|' + i.ordertype);
          } 
        })
      })
      passParams.ordercol = arr.join(',');;
      this.props.onOk(passParams);
    }

    onCancel() {
      this.props.onCancel();
    }
    render() {
      const { settingData, title, dialogHeight } = this.props;
      const {
          visible,orderColVisible, eFieldNewVisible, orderColDataSource, orderColUsedKeys,
          wfsourceSelectkey,eFieldNewDataSource, eFieldNewUsedKeys, dimensionalityDataSouce,
          dimensionalityUsedKeys, showTypeNewVisible
        } = this.state;
      
        //显示字段设置
      let EFieldNew = <div></div>;
      if (eFieldNewVisible) {
        let dataSource = _.cloneDeep(toJS(eFieldNewDataSource));
        dataSource.map( v => {
            if(!v.name || !v.id || !v.key) {
              v.name = v.fieldshowname;
              v.id = v.id;
              v.key = v.id;
            } 
        })
        const eFieldNewProps = {
            title: getLabel(32317, '显示字段设置'),
            eFieldNewDataSource: dataSource,
            eFieldNewUsedKeys: _.cloneDeep(eFieldNewUsedKeys),
            onOk: (data) => {
                this.setState({
                    eFieldNewDataSource: _.cloneDeep(data.eFieldNewDataSource),
                    eFieldNewUsedKeys: _.cloneDeep(data.eFieldNewUsedKeys),
                    eFieldNewVisible: false
                });
            },
            onCancel: () => {
                this.setState({
                    eFieldNewVisible: false
                });
            }
        };
        EFieldNew = <EField_New ecId={`${this && this.props && this.props.ecId || ''}_EField_New@aga2b7`} {...eFieldNewProps}/>
      }

      //显示维度设置
      let showTypeNew = <div></div>
      if (showTypeNewVisible) {
        let showTypeNewDataSource = _.cloneDeep(toJS(dimensionalityDataSouce));
        showTypeNewDataSource.map( v => {
            if(!v.name || !v.id || !v.key) {
              v.name = v.showname;
              v.key = v.id;
              v.id = v.id;
            } 
        })
        const showTypeNewProps = {
            title: '显示维度设置',
            eFieldNewDataSource: showTypeNewDataSource,
            eFieldNewUsedKeys: _.cloneDeep(dimensionalityUsedKeys),
            onOk: (data) => {
                this.setState({
                    dimensionalityDataSouce: _.cloneDeep(data.eFieldNewDataSource),
                    dimensionalityUsedKeys: _.cloneDeep(data.eFieldNewUsedKeys),
                    showTypeNewVisible: false
                });
            },
            onCancel: () => {
                this.setState({
                  showTypeNewVisible: false
                });
            }
        };
        EFieldNew = <EField_New ecId={`${this && this.props && this.props.ecId || ''}_EField_New@h451ir`} {...showTypeNewProps}/>
      }
    //排序字段设置
      let orderColComp = <div></div>;
      if (orderColVisible) {
        let orderSource = [];
          _.cloneDeep(toJS(orderColDataSource)).map( v => {
            if(!v.key) {
              orderSource.push({...v,key: v.id})
            } else {
              orderSource.push(v);
            }
        })
          const orderColProps = {
              orderColDataSource: orderSource,
              orderColUsedKeys: _.cloneDeep(orderColUsedKeys),
              onOk: (data) => {
                  this.setState({
                      orderColDataSource: data.orderColDataSource,
                      orderColUsedKeys: data.orderColUsedKeys,
                      orderColVisible: false
                  });
              },
              onCancel: () => {
                  this.setState({
                      orderColVisible: false
                  });
              }
          };
          orderColComp = <EOrderCol ecId={`${this && this.props && this.props.ecId || ''}_EOrderCol@ygje6e`} {...orderColProps}/>
      }


      const orderColUsedNames = [];
      for (let i = 0, len = orderColUsedKeys.length; i < len; i++) {
          for (let j = 0, len2 = orderColDataSource.length; j < len2; j++) {
              if (orderColUsedKeys[i] == orderColDataSource[j].id) {
                  orderColUsedNames.push(orderColDataSource[j].fieldshowname + '-' + (orderColDataSource[j].ordertype == '0' ? getLabel(340,"降序") : getLabel(339,"升序")));
              }
          }
      }

      const eFieldNewUsedNames = [];
      for (let i = 0; i < eFieldNewUsedKeys.length; i++) {
          for (let j = 0 ; j < eFieldNewDataSource.length; j++) {
              if (eFieldNewUsedKeys[i] == eFieldNewDataSource[j].id) {
                  eFieldNewUsedNames.push(eFieldNewDataSource[j].fieldshowname);
              }
          }
      }

      const  showTypeNewNames = [];
      for( let i = 0; i < dimensionalityUsedKeys.length; i++) {
        for( let j = 0; j < dimensionalityDataSouce.length; j++) {
          if(dimensionalityUsedKeys[i] == dimensionalityDataSouce[j].id) {
            showTypeNewNames.push(dimensionalityDataSouce[j].showname);
          }
        }
      }
    
      let orderTitles ="";
      for(let i = 0;i < orderColUsedNames.length; i++){
          orderTitles = orderTitles + orderColUsedNames[i];
      }

      let eFieldTitles ="";
      for(let i = 0;i < eFieldNewUsedNames.length; i++){
          eFieldTitles = eFieldTitles + eFieldNewUsedNames[i];
      }
      
      let content = [];
      let workflowids = toJS(settingData).condition && toJS(settingData).condition.items.filter( v => v.domkey == 'workflowids') || [];
      let workflowtypes = toJS(settingData).condition && toJS(settingData).condition.items.filter( v => v.domkey == 'workflowtypes') || [];
      if(workflowids[0] || workflowtypes[0]) {
        if(workflowids[0].browserConditionParam || workflowtypes[0].browserConditionParam)  {
          delete workflowids[0].browserConditionParam.replaceDatas;
          delete workflowtypes[0].browserConditionParam.replaceDatas;
        }
      }
      toJS(settingData).condition && 
      toJS(settingData).condition.items && 
      toJS(settingData).condition.items.length > 0 && 
      toJS(settingData).condition.items.map( v => {
        let com = null;
        switch(v.domkey[0]) {
          case ("fromType"): {
            com = (
              <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@b1esbv@fromType`} label={getLabel(21672, '流程来源')} labelCol={{span: 6}} wrapperCol={{span: 16}}>
                <div style={{width: '100%'}}>
                    <WeaSelect ecId={`${this && this.props && this.props.ecId || ''}_WeaSelect@sbx952@fromType`}
                        options={v.options}
                        value={wfsourceSelectkey}
                        onChange={value => {
                          this.setState({wfsourceSelectkey: value});
                        }}
                    />
                      <div className="wf-center-esetting-workflowSource">
                        {
                          (this.state.wfsourceSelectkey == '1' || this.state.wfsourceSelectkey == '2' ) &&  <WeaBrowser ecId={`${this && this.props && this.props.ecId || ''}_WeaBrowser@qpkw4c`}
                            onChange={(v) => {console.log(v);this.setState({workflowids: v})}} 
                            {...workflowids[0].browserConditionParam}
                            {...workflowids[0]}
                            > 
                              <button type="button" className="ant-btn ant-btn-ghost ant-btn-icon-only" style={{border:0}}>
                                <i className="anticon anticon-search"/>
                              </button>
                          </WeaBrowser> 
                        }
                        {
                          (this.state.wfsourceSelectkey == '3' || this.state.wfsourceSelectkey == '4' ) && <WeaBrowser ecId={`${this && this.props && this.props.ecId || ''}_WeaBrowser@qqeqtd`}
                              onChange={(v) => {this.setState({workflowtypes: v})}} 
                              { ...workflowtypes[0].browserConditionParam}
                            > 
                              <button type="button" className="ant-btn ant-btn-ghost ant-btn-icon-only" style={{border:0}}>
                                <i className="anticon anticon-search"/>
                              </button>
                          </WeaBrowser>
                        }
                    </div>
                </div>
              </WeaFormItem>)
              content.push(com); 
            };break;
            case('showcol'): {
              com = (
                <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@78rrfu@showcol`} label={getLabel(19495, '显示字段')} labelCol={{span: 6}} wrapperCol={{span: 16}}>
                    {EFieldNew}
                    <div style={{height: '100%', lineHeight: '23px'}}>
                        <i className="icon-coms-Flow-setting portal-esetting-btn" style={{top:5,position: "relative", zIndex: "12"}} onClick={() => this.setState({eFieldNewVisible: true})}/>
                        <div  title={eFieldTitles} style={{marginTop:-18}}>&nbsp;&nbsp;&nbsp;&nbsp;{eFieldNewUsedNames.join('，')}</div>
                    </div>
              </WeaFormItem>
            )
            content.push(com); 
          }; break;
          
          case('ordercol'): {
            com = (
              <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@ixsj7f@$ordercol`} label={getLabel(15512, '排序字段')} labelCol={{span: 6}} wrapperCol={{span: 16}}>
                    {orderColComp}
                    <div style={{height: '100%', lineHeight: '23px'}}>
                        <i className="icon-coms-Flow-setting portal-esetting-btn"  style={{top:5,position: "relative", zIndex: "12"}} onClick={() => this.setState({orderColVisible: true})}/>
                        <div  style={{marginTop:-18}} title={orderTitles}>&nbsp;&nbsp;&nbsp;&nbsp;{orderColUsedNames.join('，')}</div>
                    </div>
                </WeaFormItem>
            )
            content.push(com); 
          };break;
          
          case('showtypeids'): {
            com = (
                <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@yanw0l@$showtypeids`} label={getLabel(516868, '显示维度')} labelCol={{span: 6}} wrapperCol={{span: 16}}>
                  {showTypeNew}
                  <div style={{height: '100%', lineHeight: '23px'}}>
                      <i className="icon-coms-Flow-setting portal-esetting-btn"  style={{top:5,position: "relative", zIndex: "12"}} onClick={() => this.setState({showTypeNewVisible: true})}/>
                      <div  style={{marginTop:-18}} title={orderTitles}>&nbsp;&nbsp;&nbsp;&nbsp;{showTypeNewNames.join('，')}</div>
                  </div>
              </WeaFormItem>
            )
            content.push(com); 
          }; break;
          case('perpagewfcenter'): {
            com = (
              <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@q69m3g@$perpagewfcenter`} label={getLabel(19493, '显示条数')} labelCol={{span: 6}} wrapperCol={{span: 16}}>
                <WeaInputNumber ecId={`${this && this.props && this.props.ecId || ''}_WeaInputNumber@ooal0z@$perpagewfcenter`}
                  value={this.state.wfCount}
                  min={1}
                  max={1000}
                  step={1}
                  onChange={this.setCountChange}
                />
              </WeaFormItem>
            )
            content.push(com); 
          }; break; 
        };    
      })
    
      return (
        <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@5yfq26`}
          className="wf-center-esetting-dialog"
          visible={visible}
          title={`${getLabel(506919, '内容设置')}: ${title}`}
          icon={'icon-coms-workflow'}
          iconBgcolor={'rgb(0, 121, 222)'}
          style={{width: 600, height: dialogHeight}}
          resize={true}
          draggable={false}
          hasScroll={true}
          buttons={this.getButtons()}
          onCancel={this.onCancel}
        >
            {content}
        </WeaDialog>
      );
    }
}

export default Main;
